package com.ruoyi.system.controller;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletResponse;


import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.InvoiceGroup;
import com.ruoyi.system.domain.InvoiceRecordsVo;
import com.ruoyi.system.service.IInvoiceGroupService;
import com.ruoyi.system.util.DateUtil;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.unit.DataUnit;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.InvoiceRecords;
import com.ruoyi.system.service.IInvoiceRecordsService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 开票明细Controller
 * 
 * @author ruoyi
 * @date 2024-04-25
 */
@RestController
@RequestMapping("/system/records")
public class InvoiceRecordsController extends BaseController
{
    @Autowired
    private IInvoiceRecordsService invoiceRecordsService;
    @Autowired
    private IInvoiceGroupService invoiceGroupService;

    /**
     * 查询开票明细列表
     */
    @GetMapping("/list")
    public TableDataInfo list(InvoiceRecords invoiceRecords)
    {
        startPage();
        List<InvoiceRecords> list = invoiceRecordsService.selectInvoiceRecordsList(invoiceRecords);
        return getDataTable(list);
    }

    /**
     * 导出开票明细列表
     */
    @Log(title = "开票明细", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, InvoiceRecords invoiceRecords)
    {
        List<InvoiceRecords> list = invoiceRecordsService.selectInvoiceRecordsList(invoiceRecords);
        for (InvoiceRecords invoiceRecords1:list) {
            DecimalFormat df = new DecimalFormat("0.00##");
            Double profit = (Double.valueOf(invoiceRecords1.getProductPrice())-Double.valueOf(invoiceRecords1.getPlarnPrice()))*Double.valueOf(invoiceRecords1.getProductCount());
            invoiceRecords1.setProfit(df.format(profit));
            String productCode = invoiceRecords1.getProductCode();
            InvoiceGroup invoiceGroup = new InvoiceGroup();
            invoiceGroup.setProductCode(productCode);
            List<InvoiceGroup> invoiceGroups = invoiceGroupService.selectInvoiceGroupList(invoiceGroup);
            if(invoiceGroups!=null){
                invoiceRecords1.setProductGroup(invoiceGroups.get(0).getProductGroup());
            }
        }
        ExcelUtil<InvoiceRecords> util = new ExcelUtil<InvoiceRecords>(InvoiceRecords.class);
        util.exportExcel(response, list, "开票明细数据");
    }

    /**
     * 导出开票明细列表-供应商
     */
    @Log(title = "开票明细", businessType = BusinessType.EXPORT)
    @PostMapping("/exportProvide")
    public void exportProvide(HttpServletResponse response, InvoiceRecords invoiceRecords)
    {
        List<InvoiceRecordsVo> list = invoiceRecordsService.selectInvoiceProvideRecordsList(invoiceRecords);
        for (InvoiceRecordsVo invoiceRecords1:list) {
            String productCode = invoiceRecords1.getProductCode();
            InvoiceGroup invoiceGroup = new InvoiceGroup();
            invoiceGroup.setProductCode(productCode);
            List<InvoiceGroup> invoiceGroups = invoiceGroupService.selectInvoiceGroupList(invoiceGroup);
            if(invoiceGroups!=null){
                invoiceRecords1.setProductGroup(invoiceGroups.get(0).getProductGroup());
            }
        }
        ExcelUtil<InvoiceRecordsVo> util = new ExcelUtil<InvoiceRecordsVo>(InvoiceRecordsVo.class);
        util.exportExcel(response, list, "开票明细数据");
    }

    /**
     * 获取开票明细详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(invoiceRecordsService.selectInvoiceRecordsById(id));
    }

    /**
     * 新增开票明细
     */
    @Log(title = "开票明细", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody InvoiceRecords invoiceRecords)
    {
        return toAjax(invoiceRecordsService.insertInvoiceRecords(invoiceRecords));
    }

    /**
     * 修改开票明细
     */
    @Log(title = "开票明细", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody InvoiceRecords invoiceRecords)
    {
        return toAjax(invoiceRecordsService.updateInvoiceRecords(invoiceRecords));
    }

    /**
     * 删除开票明细
     */
    @Log(title = "开票明细", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(invoiceRecordsService.deleteInvoiceRecordsByIds(ids));
    }


    /**
     * 页面列表数据
     */
    @GetMapping("/listWebInfo")
    public TableDataInfo listWebInfo(@RequestParam(value = "productName",required = false)String productName,
                                     @RequestParam(value = "provide",required = false)String provide,
                                     @RequestParam(value = "company",required = false)String company,
                                     @RequestParam(value = "status",required = false)String status,
                                     @RequestParam(value = "productGroup",required = false)String productGroup,
                                     @RequestParam(value = "startTime",required = false)String startTime)
    {
        startPage();
        List<Map<String,Object>> list = invoiceRecordsService.listWebInfo(productName,provide,company,status,productGroup,startTime);
        Double allMoney = invoiceRecordsService.selectAllMoney(provide, startTime);
        Double sumMoney = invoiceRecordsService.selectSumProductMoney(provide, startTime);
        for (Map<String,Object> map:list) {
             String productCode = map.get("product_code").toString();
            InvoiceGroup invoiceGroup = new InvoiceGroup();
            invoiceGroup.setProductCode(productCode);
            List<InvoiceGroup> invoiceGroups = invoiceGroupService.selectInvoiceGroupList(invoiceGroup);
            if(invoiceGroups!=null){
                map.put("groupList",invoiceGroups);
            }
            map.put("allMoney",allMoney);
            map.put("sumMoney",sumMoney);
        }
        return getDataTable(list);
    }

    /**
     * 供应商开票明细
     */
    @GetMapping("/listProvideInfo")
    public TableDataInfo listProvideInfo(@RequestParam(value = "productName",required = false)String productName,
                                     @RequestParam(value = "provide",required = false)String provide,
                                     @RequestParam(value = "company",required = false)String company,
                                     @RequestParam(value = "status",required = false)String status,
                                     @RequestParam(value = "productGroup",required = false)String productGroup,
                                     @RequestParam(value = "startTime",required = false)String startTime)
    {
        startPage();
        List<Map<String,Object>> list = invoiceRecordsService.listProvideInfo(productName,provide,company,status,productGroup,startTime);
        Double allMoney = invoiceRecordsService.selectAllMoney(provide, startTime);
        for (Map<String,Object> map:list) {
            String productCode = map.get("product_code").toString();
            InvoiceGroup invoiceGroup = new InvoiceGroup();
            invoiceGroup.setProductCode(productCode);
            List<InvoiceGroup> invoiceGroups = invoiceGroupService.selectInvoiceGroupList(invoiceGroup);
            if(invoiceGroups!=null){
                map.put("groupList",invoiceGroups);
            }
            map.put("allMoney",allMoney);
        }
        return getDataTable(list);
    }



    /**
     * 月结报表
     */
    @RequestMapping("/listMoneyInfo")
    public AjaxResult listMoneyInfo( @RequestParam(value = "startTime",required = true)String startTime,
                                     @RequestParam(value = "provide",required = false)String provide1)
    {
        List<Map<String,Object>> hashMapList = new ArrayList<>();
            List<String> list = invoiceRecordsService.listProvide(provide1);
        DecimalFormat df = new DecimalFormat("0.00##");
        Double allMoney = invoiceRecordsService.selectAllMoney(provide1, startTime);
        for (String provide:list) {
                Map<String,Object> hashMap = new HashMap<>();
                //厂家
                hashMap.put("provide",provide);
                hashMap.put("allMoney",df.format(new BigDecimal(String.valueOf(allMoney)).setScale(2, RoundingMode.HALF_UP)));
                List<Map<String, Object>> maps = invoiceRecordsService.listSumMoney(provide,startTime);
                hashMap.put("yqMoney",0);
                hashMap.put("mdMoney",0);
                hashMap.put("yypj",0);
                hashMap.put("yyrhy",0);
                hashMap.put("yyzlj",0);
                hashMap.put("yylt",0);
                hashMap.put("cmpj",0);
                hashMap.put("cmrhy",0);
                hashMap.put("cmzlj",0);
                hashMap.put("cmlt",0);
                hashMap.put("jspj",0);
                hashMap.put("jsrhy",0);
                hashMap.put("jszlj",0);
                hashMap.put("jslt",0);
                hashMap.put("isFz",false);
                Double otherMoney = 0.0;
                List<Map<String, Object>> maps2 = invoiceRecordsService.listOtherMoney(provide,startTime);
                if(maps2!=null&&maps2.size()>0){
                    for (Map<String,Object> map:maps2) {
                        otherMoney = Double.valueOf(map.get("sumMoney").toString());
                    }
                }
                hashMap.put("otherMoney",df.format(new BigDecimal(String.valueOf(otherMoney)).setScale(2, RoundingMode.HALF_UP)));
                int count = 0;
                for (Map<String,Object> map:maps) {
                    if(map.get("settlement_mode")!=null && map.get("settlement_mode").equals("压库")){
                        //压库金额
                        if(map.get("status").equals("1")){
                            count++;
                        }
                        hashMap.put("yqMoney",df.format(new BigDecimal(map.get("sumMoney").toString()).setScale(2, RoundingMode.HALF_UP)));
                    }else if(map.get("settlement_mode")!=null && map.get("settlement_mode").equals("买断")){
                        //买断金额
                        if(map.get("status").equals("1")){
                            count++;
                        }
                        hashMap.put("mdMoney",df.format(new BigDecimal(map.get("sumMoney").toString()).setScale(2, RoundingMode.HALF_UP)));
                    }
                    //合金金额
                    Double totalMoney = Double.valueOf(hashMap.get("yqMoney").toString())+Double.valueOf(hashMap.get("mdMoney").toString());
                    hashMap.put("totalMoney",df.format(new BigDecimal(String.valueOf(totalMoney)).setScale(2, RoundingMode.HALF_UP)));
                }
                if(count == maps.size()){
                    hashMap.put("isFz",true);
                }
                List<Map<String, Object>> maps1 = invoiceRecordsService.listGroupMoney(provide,startTime);
                for (Map<String,Object> map:maps1) {
                    if(map.get("company")!=null && map.get("company").equals("营运公司")){
                        if(map.get("product_group")!=null &&  map.get("product_group").equals("配件")){
                            hashMap.put("yypj",df.format(new BigDecimal(map.get("groupMoney").toString()).setScale(2, RoundingMode.HALF_UP)));
                        }else if(map.get("product_group")!=null && map.get("product_group").equals("润滑油")){
                            hashMap.put("yyrhy",df.format(new BigDecimal(map.get("groupMoney").toString()).setScale(2, RoundingMode.HALF_UP)));
                        }else if(map.get("product_group")!=null && map.get("product_group").equals("制冷剂")){
                            hashMap.put("yyzlj",df.format(new BigDecimal(map.get("groupMoney").toString()).setScale(2, RoundingMode.HALF_UP)));
                        }else if(map.get("product_group")!=null && map.get("product_group").equals("轮胎")){
                            hashMap.put("yylt",df.format(new BigDecimal(map.get("groupMoney").toString()).setScale(3, RoundingMode.HALF_UP)));
                        }
                    }else if(map.get("company")!=null && map.get("company").equals("崇明巴士")){
                        if(map.get("product_group")!=null && map.get("product_group").equals("配件")){
                            hashMap.put("cmpj",df.format(new BigDecimal(map.get("groupMoney").toString()).setScale(2, RoundingMode.HALF_UP)));
                        }else if(map.get("product_group")!=null && map.get("product_group").equals("润滑油")){
                            hashMap.put("cmrhy",df.format(new BigDecimal(map.get("groupMoney").toString()).setScale(2, RoundingMode.HALF_UP)));
                        }else if(map.get("product_group")!=null && map.get("product_group").equals("制冷剂")){
                            hashMap.put("cmzlj",df.format(new BigDecimal(map.get("groupMoney").toString()).setScale(2, RoundingMode.HALF_UP)));
                        }else if(map.get("product_group")!=null && map.get("product_group").equals("轮胎")){
                            hashMap.put("cmlt",df.format(new BigDecimal(map.get("groupMoney").toString()).setScale(2, RoundingMode.HALF_UP)));
                        }
                    }else if(map.get("company")!=null && map.get("company").equals("金山巴士")){
                        if(map.get("product_group")!=null && map.get("product_group").equals("配件")){

                            hashMap.put("jspj",df.format(new BigDecimal(map.get("groupMoney").toString()).setScale(2, RoundingMode.HALF_UP)));
                        }else if(map.get("product_group")!=null && map.get("product_group").equals("润滑油")){
                            hashMap.put("jsrhy",df.format(new BigDecimal(map.get("groupMoney").toString()).setScale(2, RoundingMode.HALF_UP)));
                        }else if(map.get("product_group")!=null && map.get("product_group").equals("制冷剂")){
                            hashMap.put("jszlj",df.format(new BigDecimal(map.get("groupMoney").toString()).setScale(2, RoundingMode.HALF_UP)));
                        }else if(map.get("product_group")!=null && map.get("product_group").equals("轮胎")){
                            hashMap.put("jslt",df.format(new BigDecimal(map.get("groupMoney").toString()).setScale(2, RoundingMode.HALF_UP)));
                        }
                    }
                }
                hashMapList.add(hashMap);
            }
        return AjaxResult.success(hashMapList);
    }


    /**
     * 应付报表
     */
    @GetMapping("/listCompanyMoney")
    public AjaxResult listCompanyMoney(@RequestParam(value = "company",required = false)String company,@RequestParam(value = "time",required = false)String time) throws ParseException {
        List<Map<String,Object>> hashMapList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        if(time!=null && time.length()>0){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = time+"-01-01 00:00:00";
            Date lastDate = sdf.parse(date);
            for (int i = 0; i < 12; i++) {
                HashMap<String,Object> hashMap = new HashMap<>();
                String workDate = DateUtil.Date2String(lastDate, "yyyy-MM");
                List<Map<String, Object>> maps = invoiceRecordsService.listCompanyMoney(company,workDate);
                hashMap.put("month",workDate.substring(5,7));
                hashMap.put("data",maps);
                hashMapList.add(hashMap);
                lastDate = DateUtil.dateAddMonth(lastDate,1);
            }
        }else{
            calendar.setTime(new Date());
            calendar.set(calendar.MONTH,0);
            Date lastDate = calendar.getTime();
            for (int i = 0; i < 12; i++) {
                HashMap<String,Object> hashMap = new HashMap<>();
                String workDate = DateUtil.Date2String(lastDate, "yyyy-MM");
                List<Map<String, Object>> maps = invoiceRecordsService.listCompanyMoney(company,workDate);
                hashMap.put("month",workDate.substring(5,7));
                hashMap.put("data",maps);
                hashMapList.add(hashMap);
                lastDate = DateUtil.dateAddMonth(lastDate,1);
            }
        }
        return AjaxResult.success(hashMapList);
        }


    /**
     * 利润年度报表
     */
    @GetMapping("/listProfitMoney")
    public AjaxResult listProfitMoney(@RequestParam(value = "time",required = false)String time) throws ParseException {
        List<Map<String,Object>> hashMapList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        Map<String,Object> totalMap = new HashMap<>();
        String totalOutMoney = "0";
        String totalInMoney = "0";
        DecimalFormat df = new DecimalFormat("0.00##");
        if(time!=null && time.length()>0){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = time+"-01-01 00:00:00";
            Date lastDate = sdf.parse(date);
            for (int i = 0; i < 12; i++) {
                HashMap<String,Object> hashMap = new HashMap<>();
                String workDate = DateUtil.Date2String(lastDate, "yyyy-MM");
                List<Map<String, Object>> maps = invoiceRecordsService.selectSumProfitMoney(workDate);
                hashMap.put("month",workDate.substring(5,7));
                hashMap.put("data",maps);
                hashMapList.add(hashMap);
                if(maps.get(0)!=null){
                    if(maps.get(0).get("outMoney")!=null){
                        totalOutMoney = df.format(Double.valueOf(totalOutMoney)+Double.valueOf(maps.get(0).get("outMoney").toString()));
                    }
                    if(maps.get(0).get("inMoney")!=null){
                        totalInMoney = df.format(Double.valueOf(totalInMoney)+Double.valueOf(maps.get(0).get("inMoney").toString()));
                    }
                }
                lastDate = DateUtil.dateAddMonth(lastDate,1);
            }
        }else{
            calendar.setTime(new Date());
            calendar.set(calendar.MONTH,0);
            Date lastDate = calendar.getTime();
            for (int i = 0; i < 12; i++) {
                HashMap<String,Object> hashMap = new HashMap<>();
                String workDate = DateUtil.Date2String(lastDate, "yyyy-MM");
                List<Map<String, Object>> maps = invoiceRecordsService.selectSumProfitMoney(workDate);
                hashMap.put("month",workDate.substring(5,7));
                hashMap.put("data",maps);
                hashMapList.add(hashMap);
                if(maps!=null&&maps.size()>0){
                    if(maps.get(0).get("outMoney")!=null){
                        totalOutMoney = df.format(Double.valueOf(totalOutMoney)+Double.valueOf(maps.get(0).get("outMoney").toString()));
                    }
                    if(maps.get(0).get("inMoney")!=null){
                        totalInMoney = df.format(Double.valueOf(totalInMoney)+Double.valueOf(maps.get(0).get("inMoney").toString()));
                    }
                }
                lastDate = DateUtil.dateAddMonth(lastDate,1);
            }
        }
        totalMap.put("totalOutMoney",totalOutMoney);
        totalMap.put("totalInMoney",totalInMoney);
        hashMapList.add(totalMap);
        return AjaxResult.success(hashMapList);
    }


}
